package com.qf.file.service.impl;

import com.qf.file.controller.FileController;
import com.qf.file.dao.GifWorkDao;
import com.qf.file.model.GifWork;
import com.qf.file.model.GifWorkExample;
import com.qf.file.service.GifService;
import com.qf.file.utils.AlibabaOSSUtil;
import com.qf.file.utils.GifAndJpgUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@Service
public class GifServiceImpl implements GifService {

    @Resource
    private GifWorkDao gifWorkDao;


    @Override
    public int addGifWork(String url) {
        GifWork gifWork = new GifWork();
        gifWork.setGifUrl(url);
        gifWork.setState(0);
        return gifWorkDao.insertSelective(gifWork);
    }

    @Override
    public void createGif(File file, String fileName, String url) {
        //保存至OOS服务器一份--------不着急 t1
        AlibabaOSSUtil.uploadFile(fileName, file);
        //对文件进行截帧生成 gif 与 jgp  不着急 t2
        GifAndJpgUtil.buildGifAndJpg(file.getAbsolutePath(), 1, 50, 2, 10);

        //把 gjf 和 jpg 上传到oos一份      不着急 t3
        String videoFileName = fileName.substring(0, (fileName.lastIndexOf("."))) + ".mp4";
        String gifFIieName = fileName.substring(0, (fileName.lastIndexOf("."))) + ".gif";
        String jpgFileName = fileName.substring(0, (fileName.lastIndexOf("."))) + ".jgp";
        //gif 与 jgp 文件
        File videoFile = new File(FileController.FILE_PATH + File.separator + videoFileName);
        File gifFile = new File(FileController.FILE_PATH + File.separator + gifFIieName);
        File jpgFile = new File(FileController.FILE_PATH + File.separator + jpgFileName);
        // 上传
        String gifUrl = AlibabaOSSUtil.uploadFile(gifFIieName, gifFile);
        String jpgUrl = AlibabaOSSUtil.uploadFile(jpgFileName, jpgFile);


        //更新数据库
        GifWorkExample example = new GifWorkExample();
        //设置更新条件
        GifWorkExample.Criteria criteria = example.createCriteria();
        criteria.andVideoUrlEqualTo(url);
        //设置更新数据
        GifWork gifWork  = new GifWork();
        gifWork.setJpgUrl(jpgUrl);
        gifWork.setGifUrl(gifUrl);
        gifWork.setState(1);

        //更新数据库
        gifWorkDao.updateByExampleSelective(gifWork,example);
        //从此临时文件彻底没有用了。
        videoFile.delete();
        gifFile.delete();
        jpgFile.delete();

    }


    @Override
    public GifWork selectByVideoUrl(String videoUrl) {
        GifWorkExample example = new GifWorkExample();
        GifWorkExample.Criteria criteria = example.createCriteria();
        //查询任务进度
        criteria.andVideoUrlEqualTo(videoUrl);
        List<GifWork> gifWorks = gifWorkDao.selectByExample(example);

        if (gifWorks != null && gifWorks.size() > 0) {
            return gifWorks.get(0);
        }
        return null;
    }
}
